const express = require('express');
const router = express.Router();
const pool = require('../db/db');

// 用户相关路由处理
// 例如：用户注册、用户登录等

// 用户注册
router.post('/register', (req, res) => {
  const { username, password, name, phone } = req.body;

  pool.getConnection((err, connection) => {
    if (err) {
      res.status(500).json({ error: '系统异常' });
      return;
    }

    const query = 'INSERT INTO sys_user (username, password, name, phone) VALUES (?, ?, ?, ?)';
    connection.query(query, [username, password, name, phone], (error, results) => {
      connection.release();
      if (error) {
        res.status(400).json({ error: '注册失败' });
        return;
      }
      res.status(200).json({ message: '注册成功' });
    });
  });
});

// 用户登录
router.post('/login', (req, res) => {
  const { username, password } = req.body;

  pool.getConnection((err, connection) => {
    if (err) {
      res.status(500).json({ error: 'Internal server error' });
      return;
    }

    const query = 'SELECT * FROM sys_user WHERE username = ? AND password = ?';
    connection.query(query, [username, password], (error, results) => {
      connection.release();
      if (error) {
        res.status(400).json({ error: '无当前用户' });
        return;
      }

      if (results.length === 0) {
        res.status(401).json({ error: '密码不正确' });
        return;
      }

      const user = results[0];
      res.status(200).json({ message: '登录成功', user });
    });
  });
});


module.exports = router;
